#!/usr/bin/env python
# Copyright (c) 2014 Eugene Frolov <efrolov@mirantis.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import _mysql

from rdb.old_app import config


class MySQL_class(config.mysql):

    handles = [None, None, None, None, None, None, None, None, None, None]
    currentHandle = 0
    process = False

    def __init__(self):
        pass

    def trace(self, data):
        pass

    def ConnectToBD(self):
        index = 0
        for i in self.handles:
            self.handles[index] = _mysql.connect(
                host=self.host, user=self.login, passwd=self.passwd,
                db=self.db)
            self.handles[index].set_character_set('UTF8')
            self.handles[index].query("SET NAMES 'UTF8';")
            index += 1
        self.trace(str(self.handles))
        return self.handles

    def restoreConnect(self, oldhandleID):
        self.handles[oldhandleID] = _mysql.connect(
            host=self.host, user=self.login,
            passwd=self.passwd, db=self.db)
        self.handles[oldhandleID].set_character_set('UTF8')
        self.handles[oldhandleID].query("SET NAMES 'UTF8';")

    def query(self, sqltxt, id=0):
        try:
            self.handles[self.currentHandle].query(sqltxt)
        except _mysql.OperationalError:
            self.restoreConnect(self.currentHandle)
            self.handles[self.currentHandle].query(sqltxt)
        res = self.handles[self.currentHandle]
        self.currentHandle += 1
        if self.currentHandle < 9:
            self.currentHandle = 0
        return res
